/* eslint-disable @typescript-eslint/no-require-imports */
/*
 * @Author: jhw jiaxianshengye@gmail.com
 * @LastEditTime: 2025-07-30 19:03:21
 * @LastEditors: jhw
 * @Description: 文件描述
 */
const fs = require("node:fs");
const path = require("path");
const semver = require("semver");
const inquirer = require("inquirer");

const packagePath = path.resolve(
  __dirname,
  "./packages/components/package.json"
);
const changelogPath = path.resolve(__dirname, "./CHANGELOG.md");

// 读取当前版本
function getCurrentVersion() {
  const packageData = fs.readFileSync(packagePath, "utf8");
  return JSON.parse(packageData).version;
}

// 更新版本号
function updateVersion(newVersion) {
  const packageData = fs.readFileSync(packagePath, "utf8");
  const packageObj = JSON.parse(packageData);

  // 更新版本
  packageObj.version = newVersion;

  // 写入文件
  fs.writeFileSync(packagePath, JSON.stringify(packageObj, null, 2));

  // 更新 CHANGELOG.md
  updateChangelog(newVersion);

  return newVersion;
}

// 更新 CHANGELOG
function updateChangelog(version) {
  // const date = new Date().toISOString().split('T')[0]  // 获取当前日期
  const date = new Date().toLocaleString("zh-CN", {
    timeZone: "Asia/Shanghai",
  });
  let changelog = "";

  try {
    changelog = fs.readFileSync(changelogPath, "utf8");
  } catch (e) {
    console.log("创建新的 CHANGELOG.md 文件");
  }

  const header = `# Changelog\n\n## [${version}] - ${date}\n\n### 新增\n\n### 修改\n\n### 修复\n\n`;
  fs.writeFileSync(changelogPath, header + changelog);
}

// 主函数 - 命令行交互
async function main() {
  // 获取传过来的参数 major, minor, patch
  const args = process.argv.at(-1);
  console.log(`Received arguments: ${args}`);
  if (args && ["major", "minor", "patch"].includes(args)) {
    const currentVersion = getCurrentVersion();
    const newVersion = semver.inc(currentVersion, args);
    updateVersion(newVersion);
    console.log(`✅ 版本号已更新为: ${newVersion}`);
    return newVersion;
  }

  const currentVersion = getCurrentVersion();

  // 询问用户选择更新类型
  const { action } = await inquirer.default.prompt([
    {
      type: "list",
      name: "action",
      message: `当前版本: ${currentVersion}. 选择更新类型:`,
      choices: [
        {
          name: `主版本 (${semver.inc(currentVersion, "major")})`,
          value: "major",
        },
        {
          name: `次版本 (${semver.inc(currentVersion, "minor")})`,
          value: "minor",
        },
        {
          name: `修订号 (${semver.inc(currentVersion, "patch")})`,
          value: "patch",
        },
        // { name: '自定义版本', value: 'custom' },
      ],
    },
  ]);

  let newVersion;

  // if (action === 'custom') {
  //   const { customVersion } = await inquirer.prompt([
  //     {
  //       type: 'input',
  //       name: 'customVersion',
  //       message: '输入新版本号 (格式: x.y.z):',
  //       validate: (input) => (semver.valid(input) ? true : '请输入有效的语义化版本号'),
  //     },
  //   ])
  //   newVersion = customVersion
  // } else {
  newVersion = semver.inc(currentVersion, action);
  // }

  if (newVersion) {
    updateVersion(newVersion);
    console.log(`✅ 版本号已更新为: ${newVersion}`);
  }

  return newVersion;
}

// 导出函数供其他脚本使用
module.exports = {
  getCurrentVersion,
  updateVersion,
  main,
};

// 当直接执行此脚本时运行主函数
if (require.main === module) {
  main().catch(console.error);
}
